<?php

class Soul_Db_Sql_Update extends Soul_Db_Sql_Where {

    private $_values = array();
    private $_table = '';

    public function update($table) {
        $this->_table = $table;
        return $this;
    }

    public function set($field, $value, $type = 's') {
        $pn = 'p' . count($this->parameters);
        $this->_values[] = array(
            'name' => $this->addQualifier($field),
            'parameter' => ':' . $pn . ':' . $type
        );
        $this->addParameter($pn, $value);
        return $this;
    }

    public function reset() {
        $this->_table = '';
        $this->_values = array();
        $this->resetWhere();
        $this->resetParameter();
        return $this;
    }

    public function resetValue() {
        $this->_values = array();
        return $this;
    }

    public function toSql() {
        $sets = array();
        foreach ($this->_values as $item) {
            $sets[] = $item['name'] . '=' . $item['parameter'];
        }
        $result = 'UPDATE `' . $this->_table . '`' . ' SET ' . implode(',', $sets);
        $result .= parent::toSql();
        return $result;
    }

    public function execute($driver = NULL) {
        $sql = $this->toSql();
        $driver = is_object($driver) ? $driver : Soul_Db_Factory::getDriver($driver);
        return $driver->setSql($sql, $this->getParameters())->execute();
    }

}